//
//  TransviaMapViewController.m
//  GNAPP
//
//  Created by zzp on 2019/1/11.
//  Copyright © 2019年 zzp. All rights reserved.
//

#import "GaodeAnnoTransViaViewController.h"
#import "UIView+Utils.h"
#import <FMDB/FMDB.h>
#import "Location.h"
#import "CommonUtility.h"

static const NSInteger RoutePlanningPaddingEdge                    = 20;

@interface GaodeAnnoTransViaViewController ()<UITableViewDelegate,UITableViewDataSource,MAMapViewDelegate, AMapSearchDelegate,MAMultiPointOverlayRendererDelegate>
{
    double lastSelectChargeTime;//间隔0.1秒，防止隐藏弹框
    UIView *bottomView;
    id <MAAnnotation> seletedPointItem;
    UITableView *tableView;
    UILabel *nameLabel;
}
@property (nonatomic,strong) NSMutableArray *viaPositions;
@property (nonatomic) MAMultiPointOverlay *overlay;
@property (nonatomic, strong) MAMapView *mapView;
@property (nonatomic, strong) AMapSearchAPI *search;
/* 起始点经纬度. */
@property (nonatomic) CLLocationCoordinate2D startCoordinate;
/* 终点经纬度. */
@property (nonatomic) CLLocationCoordinate2D destinationCoordinate;

@property (nonatomic, strong) MAPointAnnotation *startAnnotation;
@property (nonatomic, strong) MAPointAnnotation *destinationAnnotation;
@property (nonatomic, strong) NSMutableArray *annotations;


@property (nonatomic, strong) AMapRoute *route;

@property (nonatomic,strong) MAPolyline *polyline;
@property (nonatomic,strong) UIView *   headView;
@end

@implementation GaodeAnnoTransViaViewController

#pragma mark - Life Cycle

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.hidden=true;
    
    self.title=@"高德Anno途径点";
    
    self.viaPositions=[NSMutableArray array];
    
    [self addHeadView];
    
    self.mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, _headView.bottom, self.view.width, self.view.height-_headView.bottom)];
    self.mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.mapView.delegate = self;
    self.mapView.centerCoordinate=[Location shareLocation].location.coordinate;
    self.mapView.zoomLevel=13;
    [self.view addSubview:self.mapView];
    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;
    
    // Do any additional setup after loading the view.
}
-(void)viewDidDisappear:(BOOL)animated{
    self.navigationController.navigationBarHidden=true;
}
-(void)viewWillAppear:(BOOL)animated{

    [self searchRoute];
    [self showDestinationAnnotation];
    
}
-(void)viewDidAppear:(BOOL)animated{
        [self initOverlay];
    self.navigationController.navigationBar.hidden=true;
}
#pragma mark - Util
-(void)addHeadView{
    
    _headView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, 200)];
    _headView.backgroundColor=[UIColor blueColor];
    [self.view addSubview:_headView];
    
    UIButton *backbt=[[UIButton alloc]initWithFrame:CGRectMake(0, 20,80, 44)];
    [backbt setTitle:@"Back" forState:UIControlStateNormal];
    [backbt setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [backbt addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    [_headView addSubview:backbt];
    
    tableView=[[UITableView alloc]initWithFrame:CGRectMake(80, 30, _headView.width-80-10,_headView.height-10-30) style:UITableViewStylePlain];
    tableView.delegate=self;
    tableView.dataSource=self;
    [_headView addSubview:tableView];
    
}

-(void)goBack{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)initOverlay
{
    
    self.annotations = [NSMutableArray array];
    
    //1.获得数据库文件的路径
    
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDirectory = [path objectAtIndex:0];
    
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"MAP" ofType:@"db"];
    NSString *dstPath = [docDirectory stringByAppendingPathComponent:@"MAP.db"];
    NSLog(@"%@",filePath);
    if(![[NSFileManager defaultManager]fileExistsAtPath:dstPath]){
        [[NSFileManager defaultManager] copyItemAtPath:filePath toPath:dstPath error:nil];
    }
    //2.获得数据库
    FMDatabase *db=[FMDatabase databaseWithPath:dstPath];
    
    int count=0;
    //3.打开数据库
    if ([db open]) {
        // 1.执行查询语句
        FMResultSet *resultSet = [db executeQuery:@"select field_3, field_12 , field_13 from bb  "];
        FMResultSet *countSet = [db executeQuery:@"select count(*) as aa from bb"];
        
        if([countSet next]){
            count=[countSet intForColumn:@"aa"];
        }
        
        CLLocationCoordinate2D coordinates[count];
        int index=0;
        // 2.遍历结果
        while ([resultSet next]) {
            double  longitude= [resultSet doubleForColumn:@"field_12"];
            double latitude = [resultSet doubleForColumn:@"field_13"];
            NSString * name = [resultSet stringForColumn:@"field_3"];
            CLLocationCoordinate2D newCoordinate =CLLocationCoordinate2DMake(latitude,longitude);
            coordinates[index]=newCoordinate;
            index++;
            MAPointAnnotation *a1 = [[MAPointAnnotation alloc] init];
            a1.coordinate = newCoordinate;
            a1.title      = name;
            [self.annotations addObject:a1];
            //              NSLog(@"resultSet %lf  %lf", ID, name);
        }
        
        
    }else{
        
        
    }
 [self.mapView addAnnotations:self.annotations];
    
}
- (void)showDestinationAnnotation
{
    /* overlays */
    //    [self.mapView removeOverlays:self.mapView.overlays];
    MAMultiPointItem *item = [[MAMultiPointItem alloc] init];
    double  longitude= self.tip.location.longitude;
    double latitude = self.tip.location.latitude;
    NSString * name = self.tip.name;
    NSString *address=self.tip.address;
    CLLocationCoordinate2D newCoordinate =CLLocationCoordinate2DMake(latitude,longitude);
    item.coordinate = newCoordinate;
    item.title=name;
    item.subtitle=address;
    
    MAAnnotationView *annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:item reuseIdentifier:@"aa"];
    annotationView.canShowCallout               = YES;
    annotationView.draggable                    = false;
    annotationView.rightCalloutAccessoryView    = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
    annotationView.image=[UIImage imageNamed:@"img_map_marker"];
    
    [self.mapView addAnnotations:@[item]];
    
}
//路线解析
- (MAPolyline *)polylinesForPath:(AMapPath *)path{
    if (path == nil || path.steps.count == 0){
        return nil;
    }
    NSMutableString *polylineMutableString = [@"" mutableCopy];
    for (AMapStep *step in path.steps) {
        [polylineMutableString appendFormat:@"%@;",step.polyline];
    }
    
    NSUInteger count = 0;
    CLLocationCoordinate2D *coordinates = [self coordinatesForString:polylineMutableString
                                                     coordinateCount:&count
                                                          parseToken:@";"];
    
    MAPolyline *polyline = [MAPolyline polylineWithCoordinates:coordinates count:count];
    
    free(coordinates);
    coordinates = NULL;
    return polyline;
}

//解析经纬度
- (CLLocationCoordinate2D *)coordinatesForString:(NSString *)string
                                 coordinateCount:(NSUInteger *)coordinateCount
                                      parseToken:(NSString *)token{
    if (string == nil){
        return NULL;
    }
    
    if (token == nil){
        token = @",";
    }
    
    NSString *str = @"";
    if (![token isEqualToString:@","]){
        str = [string stringByReplacingOccurrencesOfString:token withString:@","];
    }else{
        str = [NSString stringWithString:string];
    }
    
    NSArray *components = [str componentsSeparatedByString:@","];
    NSUInteger count = [components count] / 2;
    if (coordinateCount != NULL){
        *coordinateCount = count;
    }
    CLLocationCoordinate2D *coordinates = (CLLocationCoordinate2D*)malloc(count * sizeof(CLLocationCoordinate2D));
    
    for (int i = 0; i < count; i++){
        coordinates[i].longitude = [[components objectAtIndex:2 * i]     doubleValue];
        coordinates[i].latitude  = [[components objectAtIndex:2 * i + 1] doubleValue];
    }
    return coordinates;
}
-(void)searchRoute{
    
    self.startCoordinate        = [Location shareLocation].location.coordinate;
    self.destinationCoordinate  = CLLocationCoordinate2DMake(_tip.location.latitude, _tip.location.longitude);
    
    MAPointAnnotation *startAnnotation = [[MAPointAnnotation alloc] init];
    startAnnotation.coordinate = self.startCoordinate;
    startAnnotation.title      = @"起始点";
    startAnnotation.subtitle   = [NSString stringWithFormat:@"{%f, %f}", self.startCoordinate.latitude, self.startCoordinate.longitude];
    self.startAnnotation = startAnnotation;
    
    MAPointAnnotation *destinationAnnotation = [[MAPointAnnotation alloc] init];
    destinationAnnotation.coordinate = self.destinationCoordinate;
    destinationAnnotation.title      =@"终点";
    destinationAnnotation.subtitle   = [NSString stringWithFormat:@"{%f, %f}", self.destinationCoordinate.latitude, self.destinationCoordinate.longitude];
    self.destinationAnnotation = destinationAnnotation;
    
    AMapDrivingRouteSearchRequest *navi = [[AMapDrivingRouteSearchRequest alloc] init];
    
    navi.requireExtension = YES;
    
    /* 出发点. */
    navi.origin = [AMapGeoPoint locationWithLatitude:self.startCoordinate.latitude
                                           longitude:self.startCoordinate.longitude];
    
    //    waypoints
    if(self.viaPositions.count){
        NSMutableArray *waypoints=[NSMutableArray array];
        for (MAMultiPointItem *pointItem in self.viaPositions) {
            AMapGeoPoint *geoPoint=  [AMapGeoPoint locationWithLatitude:pointItem.coordinate.latitude
                                                              longitude:pointItem.coordinate.longitude];
            [waypoints addObject:geoPoint];
        }
        navi.waypoints=waypoints;
    }
    
    
    /* 目的地. */
    navi.destination = [AMapGeoPoint locationWithLatitude:self.destinationCoordinate.latitude
                                                longitude:self.destinationCoordinate.longitude];
    
    [self.search AMapDrivingRouteSearch:navi];
}
-(void)showBottomViewWithInfo: (id <MAAnnotation> )item{
    
    seletedPointItem=item;
    
    if(!bottomView){
        bottomView=[[UIView alloc]initWithFrame:CGRectMake(0, self.view.bottom-150, self.view.width, 150)];
        bottomView.backgroundColor=[UIColor whiteColor];
        [self.view addSubview:bottomView];
        
        nameLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, 0,bottomView.width, 35)];
        nameLabel.font=[UIFont boldSystemFontOfSize:15.0f];
        nameLabel.textAlignment=NSTextAlignmentCenter;
        nameLabel.textColor=[UIColor redColor];
        [bottomView addSubview:nameLabel];
        [self addLineviewWithFrame:CGRectMake(0, nameLabel.bottom-1, nameLabel.width, 1) onView:nameLabel];
        
        NSArray *titles=@[@"设为途径点",@"查看详细",@"取消"];
        
        
        for (int d=0; d<titles.count; d++) {
            UIButton *bt=[[UIButton alloc]initWithFrame:CGRectMake(0,nameLabel.bottom+(nameLabel.height)*d,bottomView.width, nameLabel.height )];
            [bt setTitle:titles[d] forState:UIControlStateNormal];
            [bt setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            bt.titleLabel.font=[UIFont systemFontOfSize:15.0f];
            bt.tag=1000+d;
            [bt addTarget:self action:@selector(setOrCancelVia:) forControlEvents:UIControlEventTouchUpInside];
            [self addLineviewWithFrame:CGRectMake(0, bt.height-1, bt.width, 1) onView:bt];
            [bottomView addSubview:bt];
        }
    }
    if([self.viaPositions containsObject:item]){
        UIButton *bt=(UIButton*)[bottomView viewWithTag:1000];
        [bt setTitle:@"取消途径点" forState:UIControlStateNormal];
    }
    nameLabel.text=item.title;
    bottomView.hidden=false;
}
-(void)addLineviewWithFrame:(CGRect)frame onView:(UIView*)view{
    UIView *aView=[[UIView alloc]initWithFrame:frame];
    aView.backgroundColor=[UIColor lightGrayColor];
    [view addSubview:aView];
}
-(void)setOrCancelVia:(UIButton*)bt{
    if(bt.tag==1000){
        if([self.viaPositions containsObject:seletedPointItem]){
            [self.viaPositions removeObject:seletedPointItem];
        }else{
            [self.viaPositions addObject:seletedPointItem];
        }
    }
    [tableView reloadData];
    [self searchRoute];
}
-(void)hiddenBottomView{
    bottomView.hidden=true;
}

#pragma mark - MAMapViewDelegate



- (void)mapView:(MAMapView *)mapView didAddOverlayRenderers:(NSArray *)overlayRenderers
{
    NSLog(@"overlayRenderers :%@", overlayRenderers);
}

//- (void)mapView:(MAMapView *)mapView didSingleTappedAtCoordinate:(CLLocationCoordinate2D)coordinate{
//    double timelast= [NSDate timeIntervalSinceReferenceDate];
//    if(timelast-lastSelectChargeTime>0.1){
//        [self hiddenBottomView];
//    }
//    NSLog(@"didSingleTappedAtCoordinate");
//}

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    
    static NSString *pointReuseIndetifier = @"pointReuseIndetifier";
    MAAnnotationView *annotationView = (MAPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndetifier];
    if (annotationView == nil)
    {
        annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndetifier];
    }
    
    annotationView.canShowCallout               = false;
    annotationView.draggable                    = false;
//    annotationView.rightCalloutAccessoryView    = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
    annotationView.image=[UIImage imageNamed:@"img_map_marker"];
    
    return annotationView;
}

- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay
{
    if ([overlay isKindOfClass:[MAPolyline class]])
    {
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:overlay];
        
        polylineRenderer.lineWidth   = 6.f;
        polylineRenderer.strokeColor = [UIColor blueColor];
        
        return polylineRenderer;
    }else  if ([overlay isKindOfClass:[MAMultiPointOverlay class]])
    {
        MAMultiPointOverlayRenderer * renderer = [[MAMultiPointOverlayRenderer alloc] initWithMultiPointOverlay:overlay];
        
        renderer.icon = [UIImage imageNamed:@"img_map_marker"];
        renderer.delegate = self;
        return renderer;
    }
    
    return nil;
}
/*!
 @brief 当选中一个annotation views时调用此接口
 @param mapView 地图View
 @param views 选中的annotation views
 */
- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view {

    lastSelectChargeTime=[NSDate timeIntervalSinceReferenceDate];
    [self showBottomViewWithInfo:view.annotation];
}

/*!
 @brief 当取消选中一个annotation views时调用此接口
 @param mapView 地图View
 @param views 取消选中的annotation views
 */
- (void)mapView:(MAMapView *)mapView didDeselectAnnotationView:(MAAnnotationView *)view {
    
}

/*!
 @brief 标注view的accessory view(必须继承自UIControl)被点击时调用此接口
 @param mapView 地图View
 @param annotationView callout所属的标注view
 @param control 对应的control
 */
- (void)mapView:(MAMapView *)mapView annotationView:(MAAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control {
    
}

/**
 *  标注view的calloutview整体点击时调用此接口
 *
 *  @param mapView 地图的view
 *  @param view calloutView所属的annotationView
 */
- (void)mapView:(MAMapView *)mapView didAnnotationViewCalloutTapped:(MAAnnotationView *)view {
    
}


#pragma mark - AMapSearchDelegate

- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error
{
    NSLog(@"Error: %@ - %@", error, error.description);
}
/* 路径规划搜索回调. */
- (void)onRouteSearchDone:(AMapRouteSearchBaseRequest *)request response:(AMapRouteSearchResponse *)response
{
    if (response.route == nil){
        return;
    }
    
    if (response.count > 0){
        //直接取第一个方案
        AMapPath *path = response.route.paths[0];
        //移除旧折线对象
        [_mapView removeOverlay:_polyline];
        //构造折线对象
        _polyline = [self polylinesForPath:path];
        //添加新的遮盖，然后会触发代理方法(- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay)进行绘制
        [_mapView addOverlay:_polyline];
        /* 缩放地图使其适应polylines的展示. */
        [self.mapView setVisibleMapRect:[CommonUtility mapRectForOverlays:@[_polyline]]
                            edgePadding:UIEdgeInsetsMake(RoutePlanningPaddingEdge, RoutePlanningPaddingEdge, RoutePlanningPaddingEdge, RoutePlanningPaddingEdge)
                               animated:YES];
    }
    
}
#pragma mark - MAMultiPointOverlayRendererDelegate

- (void)multiPointOverlayRenderer:(MAMultiPointOverlayRenderer *)renderer didItemTapped:(MAMultiPointItem *)item
{
    NSLog(@"item :%@ <%f, %f> name:%@", item, item.coordinate.latitude, item.coordinate.longitude,item);
    lastSelectChargeTime=[NSDate timeIntervalSinceReferenceDate];
    [self showBottomViewWithInfo:item];
}
#pragma mark - UITableViewDataSource
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 30;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return  self.viaPositions.count+2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *tipCellIdentifier = @"tipCellIdentifier";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:tipCellIdentifier];
    
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                      reuseIdentifier:tipCellIdentifier];
    }
    if(indexPath.row==0){
        cell.textLabel.text = @"从：我的位置";
    }else if(indexPath.row== (self.viaPositions.count+1)){
        cell.textLabel.text = [NSString stringWithFormat:@"到：%@",_tip.name];
    }else{
        MAMultiPointItem *pointItem=self.viaPositions[indexPath.row-1];
        cell.textLabel.text = pointItem.title;
    }
    
    return cell;
}

#pragma mark - UITableViewDelegate


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

